import shop from '../../api/shop'
import Vue from 'vue'

const state={
    items:[],
    checkoutStatus:null
}

const getters={
    cartProducts:(state,getters,rootState)=>{
        return state.items.map(({id,quantity})=>{
            const product=rootState.products.all.find(product=>product.id===id)
            return {
                title: product.title,
                price: product.price,
                quantity
            }
        })
    },

    cartTotalPrice:(state,getters)=>{
        return getters.cartProducts.reduce((total,product)=>{
            return total+product.price*product.quantity
        },0)
    }
}

const actions={
    checkout({commit,state},products){
        const saveCartItems=[...state.items]
        commit('setCheckoutStatus',null)
        //empty cart
        commit('setCartItems',{items:[]})
        shop.buyProducts(
            products,
            ()=>commit('setCheckoutStatus','successful'),
            ()=>{
                commit('setCheckoutStatus','failed')
                commit('setCartItems',{items:savedCartItems})
            }
        )
    },
    addProductToCart({state,commit},product){
        commit('setCheckoutStatus', null)
        if(product.inventory>0){
            const cartItem = state.items.find(item=>item.id===product.id)//加入购物车的产品，是否已存在于购物车列表中。
            if(!cartItem){//未存在购物车列表中
                commit('pushProductToCart',{id:product.id})
            }else{//已存在购物车列表中
                console.log(cartItem,'cartItem')
                commit('incrementItemQuantity',cartItem)
            }
            // remove 1 item from stock
            commit('products/decrementProductInventory', { id: product.id }, { root: true })
        }
    }
}

const mutations={
    pushProductToCart(state,{id}){
        state.items.push({
            id,
            quantity:1
        })
    },
    incrementItemQuantity(state,{id,quantity}){
        var a;
        const cartItem=state.items.find((item,index)=>{
            if(item.id===id){
                a = index;
            }
            return item.id===id;
        });
        // Vue.set(state.items,a,{'id':id,'quantity':++quantity})
        cartItem.quantity++;
    },
    setCartItems(state,{items}){
        state.items = items;
    },
    setCheckoutStatus(state,status){
        state.checkoutStatus = status
    }
}

export default{
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}